package cn.pugle.base.thread.ticketlock;


/**
 * @author tzp
 * @since 2018/7/6
 */
public class TicketLockTest1 {
    public static void main(String[] args) throws InterruptedException {
        TicketLock4 ticketLock = new TicketLock4();

        MyTask myTask1 = new MyTask(1L, ticketLock);
        new Thread(myTask1).start();

        MyTask myTask2 = new MyTask(1L, ticketLock);
        new Thread(myTask2).start();

    }

    static class MyTask implements Runnable {

        Long idToLock;
        TicketLock4 ticketLock;

        public MyTask(Long idToLock, TicketLock4 ticketLock) {
            this.idToLock = idToLock;
            this.ticketLock = ticketLock;
        }

        @Override
        public void run() {
            ticketLock.getLock(idToLock);
            try {
                System.out.println(Thread.currentThread() + " get lock " + idToLock);
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println(Thread.currentThread() + " quit lock area");
            } finally {
                ticketLock.removeLock(idToLock);
            }
        }
    }

}
